var appData = getApp().globalData;
var app = getApp();  
var Url = 'receive/';
var shareid;  
var list = [];
var stat = [];
Page({   
  data: {
    loading: true,
    share: false, 
    imgUrl: appData.Url + 'assets/bgimg/receiveBG.jpg',
  },
  onLoad: function (op) {
    console.log("转发携带参数", op);    
    shareid = parseInt(op.id);        // 指定邀请码
    appData.hotel = parseInt(op.ht);  // 指定门店
    const that = this;
    wx.login({
      success: function(code) {
        app.request(Url + 'login', { id: shareid, code: code.code }).then((res) => {
          var d = res.data, friends = [];
          console.log(res.name, res.data);
          appData.user.openid = res.data.openid,
          list = d.receive, stat = d.stat;
          if (d.receive) {
            for (let i = 0; i < d.receive.length; i++) {
              if (d.openid == d.receive[i].openid) that.setData({ rec: false });
              if (i > 4) continue;
              friends.push({ url: d.receive[i].avatar, total: d.receive[i].total });
            }
            that.setData({ friends: friends, number: '已有' + list.length + '个好友领取' });
          }
          else 
            that.setData({ rec: true });
          that.setData({
            owner: res.data.owner,
            receive: res.data.receive,
            stat: res.data.stat,
            loading: false,
          })
        });
      }
    })

  },
  
  rec: function(info) {
    var i = info.detail.userInfo, that = this;
    if (!i) { app.modal('领取未成功', '缺少公开信息，好友就不知道赏金发给谁了哦~'); return 0; }
    that.setData({ share: true });
    console.log(i);
    // var stat_total = stat.total ? parseInt(stat.total) + 10 : 10,
    var stat_num = parseInt(stat.giv_num) + 1,
    data = {
      openid: appData.user.openid,
      id: shareid,
      total: '10',
      nick: i.nickName,
      city: i.city,
      avatar: i.avatarUrl,
      // stat_total: stat_total,
      stat_num: stat_num,
    };
    
    console.log(data)
    app.request(Url + 'insert', data).then((res) => {
      console.log(res.name, res);
      that.setData({ rec: false })
      app.toast('领取成功', 'success');
      that.onLoad({ ht: appData.hotel, id: shareid});
    }).catch((errMsg) => {
      app.toast('领取失败');
      that.setData({ share: false });
    });
  },

  toPreload: function() {
    wx.redirectTo({ url: '../preload/preload' });
  },
  toList: function() {
    var pg = { list: list };
    wx.navigateTo({ url: 'list?list=' + JSON.stringify(list) });
  },

  onShareAppMessage: function () {
    return {
      title: '大家都在抢，酒店免费住！',
      path: '/pages/index/receive/receive?id=' + shareid + '&ht=' + appData.hotel,
      imageUrl: appData.Url + 'assets/share/share2.jpg',
      suaccess: function (res) {
        console.log(res);
        wx.showShareMenu({
          withShareTicket: true,
        })
      },
      fail: function (res) {
        console.log(res)
      }
    }
  }
})